package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.*;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.SkuService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper,Spu> implements SpuService {
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryServiceImpl categoryService;
    @Autowired
    SpuDetailService spuDetailService;
    @Autowired
    SkuService skuService;
    @Autowired
    AmqpTemplate amqpTemplate;
    @Override
    public PageDTO<SpuDTO> queryByPag(Integer page, Integer rows, Boolean saleable, Long categoryId, Long brandId, Long id) {
       //当page或者rows为空的时候 使用默认值
        if (page==null){
            page=1;
        };
        if (rows==null){
            rows=5;
        }
        //开始查询
        Page<Spu> page1 = query().eq(saleable != null, "saleable", saleable)
                .eq(categoryId != null, "cid3", categoryId)
                .eq(brandId != null, "brand_id", brandId)
                .eq(id != null, "id", id)
                .page(new Page<>(page, rows));
        //解析
        //获取总数量
        long total = page1.getTotal();
        //分页数量
        long pages = page1.getPages();
        //显示的数据
        List<Spu> records = page1.getRecords();
        //转换类型
        List<SpuDTO> spuDTOS = SpuDTO.convertEntityList(records);
        for (SpuDTO spuDTO : spuDTOS) {
            //获取sku的分类和品牌名称
            handleCategoryAndBrandName(spuDTO);
        }

        return new PageDTO<>(total,pages,spuDTOS);
    }

    @Override
    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        Spu spu = spuDTO.toEntity(Spu.class);
        spu.setSaleable(false);
        boolean save = save(spu);
        if (!save){
            throw new LyException(500,"新增失败");
        }
        //新增商品详情
        SpuDetailDTO spuDetail = spuDTO.getSpuDetail();
        SpuDetail spuDetail1 = spuDetail.toEntity(SpuDetail.class);
        spuDetail1.setSpuId(spu.getId());
        boolean save1 = spuDetailService.save(spuDetail1);
        if (!save1){
            throw new LyException(500,"新增商品详情失败");
        }
        //新增sku
        List<SkuDTO> skus = spuDTO.getSkus();
        ArrayList<Sku> skus1 = new ArrayList<>();
        for (SkuDTO skuDTO : skus) {
            Sku sku = skuDTO.toEntity(Sku.class);
            sku.setSaleable(false);
            sku.setSpuId(spu.getId());
            skus1.add(sku);
        }
        skuService.saveBatch(skus1);

    }

    @Override
    @Transactional
    public void updateSaleable(Long id, boolean saleable) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        boolean b = updateById(spu);
        if (!b){
            throw new LyException(500,"更新失败");
        }
        boolean update = skuService.update().eq("spu_id", id).set("saleable", saleable).update();
        if (!update){
            throw new LyException(500,"更新失败");
        }
        //发送mq消息
        String s = saleable ? MQConstants.RoutingKeyConstants.ITEM_UP_KEY : MQConstants.RoutingKeyConstants.ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(MQConstants.ExchangeConstants.ITEM_EXCHANGE_NAME,s,id);
    }

    @Override
    public SpuDTO querySpuById(Long id) {
        //查询spu sku spudetail最后拼接
        //1.查询spu
        Spu byId = getById(id);
        if (byId==null){
            throw new LyException(400,"商品不存在");
        }
        SpuDTO spuDTO = new SpuDTO(byId);
        //2.查询spudeatail
        SpuDetail byId1 = spuDetailService.getById(id);
        if (byId1==null){
            throw new LyException(400,"商品不存在");
        }
        //封装到spu
        spuDTO.setSpuDetail(new SpuDetailDTO(byId1));
        //3查询sku
        List<Sku> spu_id = skuService.query().eq("spu_id", id).list();
        if (CollectionUtils.isEmpty(spu_id)){
            throw new LyException(400,"商品不存在");
        }
        spuDTO.setSkus(SkuDTO.convertEntityList(spu_id));
        //spu中的分类和品牌还是空值
        //准备商品分类和品牌
        handleCategoryAndBrandName(spuDTO);
        //封装完成返回
        return spuDTO;
    }

    @Override
    @Transactional
    public void updateSpu(SpuDTO spuDTO) {
        //更新商品
        //1 判断是否存在spu的id 有修改 无不修改
        if (spuDTO.getId()!=null){
            //不等于空 有修改
            Spu spu = spuDTO.toEntity(Spu.class);
            //禁止修改saleable
            spu.setSaleable(null);
            boolean b = updateById(spu);
            if (!b){
                throw  new LyException(500,"更新失败");
            }
        }
        //2修改spudetail
        SpuDetailDTO spuDetail = spuDTO.getSpuDetail();
        //判断是否为空和商品id是否为空
        if (spuDetail!=null&&spuDetail.getSpuId()!=null){
            SpuDetail spuDetail1 = spuDetail.toEntity(SpuDetail.class);
            boolean b = spuDetailService.updateById(spuDetail1);
            if (!b){
                throw  new LyException(500,"更新失败");
            }
        }
        //3更新sku
        List<SkuDTO> skus = spuDTO.getSkus();
        //判断是否存在
        if (CollectionUtils.isEmpty(skus)){
            return;
        }
        ArrayList<Sku> skus1 = new ArrayList<>();
        ArrayList<Sku> false_sku = new ArrayList<>();
        for (SkuDTO skuDTO : skus) {
            Sku sku = skuDTO.toEntity(Sku.class);
            Boolean saleable = sku.getSaleable();
            if (saleable==null){
                skus1.add(sku);
            }
           false_sku.add(sku);
        }
        //判断是否为空 不为空则新增或修改
        if (!CollectionUtils.isEmpty(skus1)){
            skuService.saveOrUpdateBatch(skus1);
        }

        //判断删除的是否为空
        if (!CollectionUtils.isEmpty(false_sku)){
            //建立一个集合 存放失败的id 统一删除
            ArrayList<Long> longs = new ArrayList<>();
            for (Sku sku : false_sku) {
                longs.add(sku.getId());
            }
            skuService.removeByIds(longs);
        }
    }

    private void handleCategoryAndBrandName(SpuDTO spuDTO) {
        //根据id查询品牌名称
        Brand byId = brandService.getById(spuDTO.getBrandId());
        if (byId!=null){
            spuDTO.setBrandName(byId.getName());
        }
        // 根据三级分类id查询分类集合
        List<Category> categories = categoryService.listByIds(spuDTO.getCategoryIds());
        if (!CollectionUtils.isEmpty(categories)){
            String collect = categories.stream().map(Category::getName).collect(Collectors.joining("/"));



            spuDTO.setCategoryName(collect);
        }
    }
}
